package com.lcf.framework.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.utils.ServletUtils;
import com.lcf.framework.utils.UserUtils;
import com.lcf.system.entity.SysTenantUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import static com.lcf.framework.constant.SysConstant.DEFAULT_TENANT_ID;


/**
 * 描述：租户拦截器
 *
 * @author lcf
 * @since 2025/4/16 18:46
 */
@Component
public class TenantInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean isLogin = ServletUtils.getRequest() != null && StpUtil.isLogin();
        if (isLogin) {
            SysTenantUser sysTenantUser = Db.lambdaQuery(SysTenantUser.class).eq(SysTenantUser::getUserId, UserUtils.getUserId()).one();
            UserUtils.setTenantId(sysTenantUser == null ? DEFAULT_TENANT_ID : sysTenantUser.getTenantId());
        } else {
            UserUtils.setTenantId(DEFAULT_TENANT_ID);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除租户 ID
        UserUtils.clearTenantId();
    }
}
